<template>
  <el-row>
    <el-card>
      <el-form ref="searchForm" :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item :label="$t('financeModule.list.createDate')">
          <el-date-picker
            v-model="searchForm.createDate"
            type="daterange"
            range-separator="~"
            :start-placeholder="$t('common.startDate')"
            :end-placeholder="$t('common.endDate')"
          />
        </el-form-item>
        <el-form-item :label="$t('financeModule.list.repayTime')">
          <el-date-picker
            v-model="searchForm.repayTime"
            type="daterange"
            range-separator="~"
            :start-placeholder="$t('common.startDate')"
            :end-placeholder="$t('common.endDate')"
          />
        </el-form-item>
        <el-form-item :label="$t('financeModule.list.RepayTimeShould')">
          <el-date-picker
            v-model="searchForm.planTime"
            type="daterange"
            range-separator="~"
            :start-placeholder="$t('common.startDate')"
            :end-placeholder="$t('common.endDate')"
          />
        </el-form-item>
        <el-form-item :label="$t('financeModule.list.userGrade')">
          <el-select v-model="searchForm.userGrade" multiple collapse-tags clearable :placeholder="$t('common.select')">
            <el-option
              v-for="item in userGradeData"
              :key="item.id"
              :label="item['userLevelName']"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('financeModule.list.packageName')">
          <el-select v-model="searchForm.packageName" multiple collapse-tags clearable :placeholder="$t('common.select')" style="width: 350px">
            <el-option
              v-for="item in packageData"
              :key="item.packageName"
              :label="item.packageName"
              :value="item.packageName"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('financeModule.list.limit')">
          <el-row>
            <el-col :span="13">
              <el-select v-model="searchForm.loanDaysFlag" clearable :placeholder="$t('common.select')">
                <el-option
                  v-for="item in $t('financeModule.list.operatorData')"
                  :key="item.value"
                  :label="item.desc"
                  :value="item.value"
                />
              </el-select>
            </el-col>
            <el-col :span="11">
              <el-input v-model="searchForm.loanDays" type="number" :placeholder="$t('financeModule.list.days')" :maxlength="50" />
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item :label="$t('financeModule.list.reBorrow')">
          <el-select v-model="searchForm.firstLoan">
            <el-option
              v-for="item in $t('financeModule.list.borrowData')"
              :key="item.value"
              :label="item.desc"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <!--          产品类型-->
        <el-form-item :label="$t('financeModule.list.orderType')">
          <el-select v-model="searchForm.orderType" multiple collapse-tags clearable :placeholder="$t('common.select')" style="width: 350px">
            <el-option
              v-for="item in $t('financeModule.list.type')"
              :key="item.value"
              :label="item.desc"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <!--          渠道来源-->
        <el-form-item :label="$t('financeModule.list.channelSource')">
          <el-select v-model="searchForm.channel" clearable :placeholder="$t('usrModule.list.prompt.channelSource')">
            <el-option
              v-for="item in $t('financeModule.list.source')"
              :key="item.value"
              :label="item.desc"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <!--            推广方式-->
        <el-form-item :label="$t('financeModule.list.promotionMethod')">
          <el-select v-model="searchForm.promotionTypeStr" clearable multiple collapse-tags :placeholder="$t('usrModule.list.prompt.promotionMethod')">
            <el-option
              v-for="item in promotionData"
              :key="item.value"
              :label="item.desc"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <!-- 推荐人 -->
        <el-form-item :label="$t('financeModule.list.referrer')">
          <el-input v-model="searchForm.referrerName" :placeholder="$t('common.input')" :maxlength="50" />
        </el-form-item>
        <!--        订单状态-->
        <el-form-item :label="$t('financeModule.list.detail.orderStatus')">
          <el-select v-model="orderStatus" multiple collapse-tags clearable :placeholder="$t('common.select')" style="width: 280px">
            <el-option
              v-for="(item, index) in $t('financeModule.list.orderStatusList')"
              :key="index"
              :label="item.desc"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <!--          待还款状态:-->
        <el-form-item :label="$t('financeModule.list.detail.PayPendStatus')">
          <el-select v-model="PayPendStatus" multiple collapse-tags clearable :placeholder="$t('financeModule.list.prompt.PayPendStatus')">
            <el-option
              v-for="(item, index) in $t('financeModule.list.PayPendStatusList')"
              :key="index"
              :label="item.desc"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <!--          订单结清类型:-->
        <el-form-item :label="$t('financeModule.list.detail.orderSettlementType')">
          <el-select v-model="orderSettlementType" multiple collapse-tags clearable :placeholder="$t('financeModule.list.prompt.orderSettlementType')">
            <el-option
              v-for="(item, index) in $t('financeModule.list.orderSettlementTypeList')"
              :key="index"
              :label="item.desc"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <!--          订单关闭类型:-->
        <el-form-item :label="$t('financeModule.list.detail.orderCloseType')">
          <el-select v-model="orderCloseType" multiple collapse-tags clearable :placeholder="$t('financeModule.list.prompt.orderCloseType')">
            <el-option
              v-for="(item, index) in $t('financeModule.list.orderCloseTypeList')"
              :key="index"
              :label="item.desc"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('financeModule.list.detail.orderNo')">
          <el-input v-model="searchForm.orderNo" :placeholder="$t('financeModule.list.prompt.orderNo')" :maxlength="50" />
        </el-form-item>
        <el-form-item :label="$t('financeModule.list.detail.letterReview')">
          <el-input v-model="searchForm.creditOrderNo" :placeholder="$t('financeModule.list.prompt.letterReview')" :maxlength="50" />
        </el-form-item>
        <el-form-item :label="$t('financeModule.list.detail.mobile')">
          <el-input v-model="searchForm.phoneNumber" :placeholder="$t('financeModule.list.prompt.mobile')" :maxlength="50" />
        </el-form-item>
        <el-form-item :label="$t('financeModule.list.detail.userName')">
          <el-input v-model="searchForm.userName" :placeholder="$t('financeModule.list.prompt.userName')" :maxlength="50" />
        </el-form-item>
        <el-row>
          <el-button type="primary" @click="search">
            {{ $t('common.search') }}
          </el-button>
          <el-button @click="reset">
            {{ $t('common.reset') }}
          </el-button>
          <el-button :disabled="!(totalNumber > 0)" @click="downloadPageNameList">
            {{ $t('common.ex') }}
          </el-button>
        </el-row>
      </el-form>
    </el-card>
    <el-card>
      <el-table
        v-loading="loading"
        :header-cell-style="{background:'#eef1f6',color:'#606266'}"
        :data="tableData"
        border
        :stripe="true"
        class="Top"
        style="width: 100%"
      >
        <el-table-column
          fixed="left"
          prop="orderNo"
          :label="tableText['orderNo']"
          min-width="150"
        >
          <template slot-scope="scope">
            <el-button type="text" @click="orderDetail(scope.row)">
              {{ scope.row.orderNo }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column
          fixed="left"
          prop="creditOrderNo"
          :label="tableText['letterReview']"
          min-width="170"
        >
          <template slot-scope="scope">
            <el-button type="text" @click="auth(scope.row)">
              {{ scope.row.creditOrderNo }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column
          prop="createTimeStr"
          :label="tableText['createTime']"
          min-width="150"
        />
        <el-table-column
          prop="userAccount"
          :label="tableText['userNo']"
          min-width="150"
        />
        <el-table-column
          prop="userName"
          :label="tableText['userName']"
          min-width="150"
        />
        <el-table-column
          prop="userGrade"
          :label="tableText['userLevel']"
          min-width="150"
        />
        <el-table-column
          prop="channelStr"
          :label="tableText['channelSource']"
          min-width="150"
        />
        <el-table-column
          prop="promotionTypeStr"
          :label="tableText['promotionMethod']"
          min-width="150"
        />
        <el-table-column
          prop="referrerName"
          :label="tableText['referrer']"
          min-width="150"
        />
        <el-table-column
          prop="orderType"
          :label="tableText['productType']"
          min-width="150"
        >
          <template slot-scope="scope">
            {{ $t('orderList.allList.productType')[scope.row['orderType']] }}
          </template>
        </el-table-column>
        <el-table-column
          prop="applyMoney"
          :label="tableText['applyCash']"
          min-width="150"
        />
        <el-table-column
          prop="loanDays"
          :label="tableText['limit']"
          min-width="150"
        />
        <el-table-column
          prop="totalPeriod"
          :label="tableText['borrowingPeriod']"
          min-width="150"
        />
        <el-table-column
          prop="packageName"
          :label="tableText['packageName']"
          min-width="150"
        />
        <el-table-column
          prop="payMoney"
          :label="tableText['payMoney']"
          min-width="150"
        />
        <el-table-column
          prop="payDateStr"
          :label="tableText['realPayMoneyTime']"
          min-width="150"
        />
        <el-table-column
          prop="currentRepay"
          :label="tableText['repayMoneyShould']"
          min-width="150"
        />
        <el-table-column
          prop="principal"
          :label="tableText['principal']"
          min-width="150"
        />
        <el-table-column
          prop="interestMoney"
          :label="tableText['interest']"
          min-width="150"
        />
        <el-table-column
          prop="otherCost"
          :label="tableText['otherFee']"
          min-width="190"
        />
        <el-table-column
          prop="overDueFine"
          :label="tableText['overdueFee']"
          min-width="150"
        />
        <el-table-column
          prop="autoEndPercent"
          :label="tableText['autoClear']"
          min-width="150"
        >
          <template slot-scope="scope">
            {{ scope.row['autoEndPercent'] ? scope.row['autoEndPercent'] + " %" : '' }}
          </template>
        </el-table-column>
        <el-table-column
          prop="realRepayMoney"
          :label="tableText['realRepayMoney']"
          min-width="180"
        />
        <el-table-column
          prop="realRepaymentDateStr"
          :label="tableText['repaymentDate']"
          min-width="150"
        />
        <el-table-column
          prop="orderStatus"
          :label="tableText['clearType']"
          min-width="150"
        >
          <template slot-scope="scope">
            <span v-if="scope.row.orderStatus.value === 15 || scope.row.orderStatus ===16 || scope.row.orderStatus=== 17|| scope.row.orderStatus === 19 || scope.row.orderStatus === 20|| scope.row.orderStatus === 21">
              {{ setState(scope.row.orderStatus, 'orderStatusEnum') }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          fixed="right"
          prop="dueDays"
          :label="tableText['dueDay']"
          min-width="150"
        />
        <el-table-column
          fixed="right"
          prop="orderStatus"
          :label="tableText['orderStatus']"
          min-width="150"
        >
          <template slot-scope="scope">
            {{ setState(scope.row.orderStatus, 'orderStatusEnum') }}
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <el-pagination
          :current-page="searchForm.currentPage"
          :page-sizes="[10, 20, 30, 40, 50]"
          :page-size="searchForm.pageSize"
          :total="totalNumber"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </el-row>
</template>

<script>
import { getUserLevel, getPageNameList, orderUnionQuery, downloadPageNameList } from '@/api/user'
import { formatDate, ObjToQueryString } from '@/utils/method'
export default {
  name: 'OrderList',
  data() {
    return {
      loading: false,
      tableData: [],
      tableText: {},
      totalNumber: 0,
      promotionData: [],
      orderStatus: ['1', '3', '-100', '15,16,17,19,20,21', '8,9,11,12,22,23,24,27'],
      PayPendStatus: [],
      orderSettlementType: [],
      orderCloseType: [],
      searchForm: this.params(),
      userGradeData: [],
      packageData: []
    }
  },
  mounted() {
    this.tableText = this.$t('orderList.allList.table')
    this.getUserLevelData()
    this.getPackageData()
    this.getData()
  },
  methods: {
    params() {
      return {
        createDate: [new Date(), new Date()],
        repayTime: null,
        planTime: null,
        currentPage: 1,
        pageSize: 10,
        userId: this.$route.query.userId ? this.$route.query.userId : null,
        createTimeStart: null,
        createTimeEnd: null,
        payDateStart: null,
        payDateEnd: null,
        planRepaymentDateStart: null,
        planRepaymentDateEnd: null,
        userGrade: [],
        packageName: [],
        loanDaysFlag: 0,
        loanDays: null,
        firstLoan: '',
        orderType: [1, 2, 3, 4],
        channel: '',
        promotionTypeStr: null,
        referrerName: null,
        orderStatus: null,
        orderNo: null,
        creditOrderNo: null,
        phoneNumber: null,
        userName: null
      }
    },
    getUserLevelData() {
      const data = {
        isPage: false
      }
      getUserLevel(data)
        .then(res => {
          if (res.success) {
            const arr = (res.data).filter(item => {
              return item['status'] === 1
            })
            arr.forEach(v => {
              this.searchForm.userGrade.push(v.id)
            })
            this.userGradeData = arr
          } else {
            this.$message.error(res.message)
          }
        })
        .catch(err => {
          this.$message.error(err.message)
        })
    },
    getPackageData() {
      getPageNameList()
        .then(res => {
          if (res.success) {
            const arr = (res.data).filter(item => {
              return item.packageName
            })
            arr.forEach(v => {
              this.searchForm.packageName.push(v.packageName)
            })
            this.packageData = arr
          } else {
            this.$message.error(res.message)
          }
        })
        .catch(err => {
          this.$message.error(err.message)
        })
    },
    setState(state, data) {
      const map = this.$t('orderList.allList')[data]
      const name = map.filter(item => {
        return item.value === state
      })
      return (name && name[0] && name[0].desc) ? name[0].desc : ''
    },
    search() {
      this.searchForm.currentPage = 1
      this.getData()
    },
    reset() {
      this.getUserLevelData()
      this.getPackageData()
      this.searchForm = this.params()
      this.time = null
      this.getData()
    },
    FlatArr(arr) {
      if (arr) {
        while (arr.some(t => Array.isArray(t))) {
          arr = ([]).concat.apply([], arr)
        }
      }
      return arr
    },
    searchData() {
      const data = {
        pageSize: this.searchForm.pageSize,
        currentPage: this.searchForm.currentPage,
        userId: this.searchForm.userId,
        loanDaysFlag: this.searchForm.loanDaysFlag,
        loanDays: this.searchForm.loanDays,
        creditOrderNo: this.searchForm.creditOrderNo,
        orderNo: this.searchForm.orderNo,
        referrerName: this.searchForm.referrerName,
        phoneNumber: this.searchForm.phoneNumber,
        userName: this.searchForm.userName,
        firstLoan: this.searchForm.firstLoan,
        channel: this.searchForm.channel,
        columns: this.searchForm.columns,
        orderBy: this.searchForm.orderBy
      }
      if (this.searchForm.createDate && this.searchForm.createDate.length > 1) {
        data['createTimeStart'] = formatDate(new Date(this.searchForm.createDate[0]), 'yyyy-MM-dd') + ' 00:00:00'
        data['createTimeEnd'] = formatDate(new Date(this.searchForm.createDate[1]), 'yyyy-MM-dd') + ' 23:59:59'
      }
      if (this.searchForm.repayTime && this.searchForm.repayTime.length > 1) {
        data['payDateStart'] = formatDate(new Date(this.searchForm.repayTime[0]), 'yyyy-MM-dd') + ' 00:00:00'
        data['payDateEnd'] = formatDate(new Date(this.searchForm.repayTime[1]), 'yyyy-MM-dd') + ' 23:59:59'
      }
      if (this.searchForm.planTime && this.searchForm.planTime.length > 1) {
        data['planRepaymentDateStart'] = formatDate(new Date(this.searchForm.planTime[0]), 'yyyy-MM-dd') + ' 00:00:00'
        data['planRepaymentDateEnd'] = formatDate(new Date(this.searchForm.planTime[1]), 'yyyy-MM-dd') + ' 23:59:59'
      }
      data['orderStatusList'] = []
      data['status'] = []
      if (this.orderStatus.length > 0) {
        const stateData = []
        this.orderStatus.forEach(v => {
          v.split(',').forEach(v => {
            stateData.push(v - 0)
          })
        })
        const arr = Array.from(new Set(this.FlatArr(stateData)))
        const num = arr.indexOf(-100)
        if (num > -1) {
          arr.splice(num, 1)
          data['status'] = [...new Set([1, 11])]
          data['orderStatusList'] = Array.from(new Set(data['orderStatusList'].concat(arr)))
          if (this.PayPendStatus.length > 0) {
            data['orderStatusList'] = Array.from(new Set(data['orderStatusList'].concat(this.PayPendStatus)))
          } else {
            data['orderStatusList'] = Array.from(new Set(data['orderStatusList'].concat([4, 5])))
          }
        } else {
          data['orderStatusList'] = Array.from(new Set(data['orderStatusList'].concat(arr)))
        }
      }
      if (this.orderSettlementType.length === 0) {
        data['orderStatusList'] = Array.from(new Set(data['orderStatusList'].concat([15, 16, 17, 19, 20, 21])))
      } else {
        data['orderStatusList'] = Array.from(new Set(data['orderStatusList'].concat(this.orderSettlementType)))
      }
      if (this.orderCloseType.length === 0) {
        data['orderStatusList'] = Array.from(new Set(data['orderStatusList'].concat([8, 12, 9, 11, 22, 23, 24])))
      } else {
        data['orderStatusList'] = Array.from(new Set(data['orderStatusList'].concat(this.orderCloseType)))
      }
      return data
    },
    getData() {
      this.loading = true
      const data = this.searchData()
      orderUnionQuery(data)
        .then(res => {
          this.loading = false
          if (res.success) {
            this.tableData = res.data
            this.totalNumber = res.page ? res.page['totalNumber'] : 0
          } else {
            this.$message.error(res.message)
          }
        })
        .catch(err => {
          this.loading = false
          this.$message.error(err.message)
        })
    },
    downloadPageNameList() {
      const data = this.searchData()
      downloadPageNameList(data)
    },
    orderDetail(item) {
      const paramData = {
        orderId: item['id'],
        userId: item['userId']
      }
      const para = ObjToQueryString(paramData)
      window.open(`${window.location.origin + window.location.pathname}#/order/detail?${para}`, '_blank')
    },
    auth(item) {
      const paramData = {
        from: 'orderList',
        status: item['orderStatus'],
        userId: item['userId'],
        orderId: item['creditOrderId'],
        orderNo: item['creditOrderNo']
      }
      const para = ObjToQueryString(paramData)
      window.open(`${window.location.origin + window.location.pathname}#/usr/auth?${para}`, '_blank')
    },
    handleSizeChange(val) {
      this.searchForm.pageSize = val
      this.getData()
    },
    handleCurrentChange(val) {
      this.searchForm.currentPage = val
      this.getData()
    },
    info(item) {
      const paramData = {
        from: 'user',
        userId: item.id
      }
      const para = ObjToQueryString(paramData).substring(-1)
      window.open(`${window.location.origin + window.location.pathname}#/usr/detail?${para}`, '_blank')
    }
  }
}
</script>

<style lang="scss" scoped>
.el-card{
  margin-top: 10px;
}
.el-tree{
  width: 100%;
}
</style>
